package com.water.dmdb.auto;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class AutowiredTest {
   private static Map<String,Object> beans = new ConcurrentHashMap<>();
    public static void main(String[] args) {
        MyController myController = new MyController();
        MyController1 myController1 = new MyController1();
        //简单的自动装配
        buildAutowired(myController,myController1);
        myController.print();
        myController1.print();
    }

    //传入需要专配的对象
    public static void buildAutowired(Object... objs) {
        for (Object obj : objs) {
            Class<?> clazz = obj.getClass();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                //获取属性 是否有注解
                MyAutowired annotation = field.getAnnotation(MyAutowired.class);
                if (annotation != null) {
                    field.setAccessible(true);
                    //获取当前属性的类型，有了类型后可以创建具体对象
                    Class<?> type = field.getType();
                    //创建具体对象
                    Object o = null;
                    try {
                        o = type.newInstance();
                        field.set(obj, o);
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }

                }

            }
        }
    }
}
